﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using FluentValidation.Validators;

using CloudSoft.Extensions;

namespace ERPStore.Validators
{
	public class PhoneNumberValidator<T, TElement> : PropertyValidator
	{
		private Func<T, Models.Country> m_Predicate;
		private Models.Country m_Country;

		public PhoneNumberValidator(Models.Country country)
			: base("invalid phone number for {propertyName}")
		{
			m_Country = country;
		}

		public PhoneNumberValidator(Func<T, Models.Country> predicate)
			: base("invalid phone number for {propertyName}")
		{
			m_Predicate = predicate;
		}

		protected override bool IsValid(PropertyValidatorContext context)
		{
			var phoneNumber = context.PropertyValue as string;
			if (phoneNumber == null)
			{
				return true;
			}

			var country = m_Country ?? m_Predicate.Invoke((T)context.Instance);

			string pattern = "";
			if (country == ERPStore.Models.Country.FRA)
			{
				pattern = @"^(\+[\s\d]{6,}|[\s\d]{6,})";
			}

			if (!pattern.IsNullOrTrimmedEmpty())
			{
				if (!System.Text.RegularExpressions.Regex.Match(phoneNumber, pattern).Success)
				{
					return false;
				}
			}

			return true;
		}
	}
}
